/*
 * ButtonPad.cpp
 *
 *  Created on: Nov 6, 2011
 *      Author: Ben
 */

#include "ButtonPad.h"
#include <WProgram.h>

ButtonPad::ButtonPad(uint8_t _ledPin, uint8_t _b1Pin, uint8_t _b2Pin, uint8_t _b3Pin)
: ObservableBounce(0, 10) {
  ledPin = _ledPin;
  b1Pin = _b1Pin;
  b2Pin = _b2Pin;
  b3Pin = _b3Pin;
}

void ButtonPad::init() {
  // Initially set up the pins
  pinMode(ledPin, OUTPUT);
  pinMode(b1Pin, INPUT);
  pinMode(b3Pin, INPUT);
  pinMode(b2Pin, INPUT);
  digitalWrite(b1Pin, HIGH);
  digitalWrite(b1Pin, HIGH);
  digitalWrite(b1Pin, HIGH);
  analogWrite(ledPin, 255);
}


// Protected: debounces the pin
int ButtonPad::debounce() {

  uint8_t newState = getButtonState();
  if (state != newState) {
    if (millis() - previous_millis >= interval_millis) {
      previous_millis = millis();
      state = newState;
      return 1;
    }
  }

  return 0;

}

uint8_t ButtonPad::getButtonState() {
  // Initially set all buttons as inputs, and pull them up
  pinMode(b2Pin, INPUT);
  digitalWrite(b2Pin, HIGH);
  pinMode(b1Pin, INPUT);
  digitalWrite(b1Pin, HIGH);
  pinMode(b3Pin, INPUT);
  digitalWrite(b3Pin, HIGH);

  // Read the d/u/flame buttons
  if (!digitalRead(b3Pin))
    return BUTTON_DOWN;  // Down
  if (!digitalRead(b2Pin))
    return BUTTON_UP;  // Up
  if (!digitalRead(b1Pin))
    return BUTTON_CENTER;  // Flame

  // Read right button
  pinMode(b2Pin, OUTPUT);  // set p52 to output, set low
  digitalWrite(b2Pin, LOW);
  if (!digitalRead(b2Pin))
    return BUTTON_RIGHT;  // Right
  pinMode(b2Pin, INPUT);  // set p52 back to input and pull-up
  digitalWrite(b2Pin, HIGH);

  // Read left button
  pinMode(b1Pin, OUTPUT);  // Set p51 to output and low
  digitalWrite(b1Pin, LOW);
  if (!digitalRead(b1Pin))
    return BUTTON_LEFT;  // Left
  pinMode(b1Pin, INPUT);  // Set p51 back to input and pull-up
  pinMode(b1Pin, HIGH);

  return 0;
}
